package com.zeus.data.jdbc;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author magic
 * @date 2018/9/5/005 10:35
 * @version 1.0
 * Description DruidAutoConfiguration
 */
@Configuration
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnClass(DruidDataSource.class)
@EnableConfigurationProperties(DruidProperties.class)
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
public class DruidAutoConfiguration{

    private static final String DATASOURCE_NAME = "datasource";

    @Bean(name = DruidAutoConfiguration.DATASOURCE_NAME)
    @ConditionalOnMissingBean(name = DruidAutoConfiguration.DATASOURCE_NAME)
    @Primary
    public DataSource dataSource(DruidProperties configDruidProperties) {

        Map<String,Object> druidProperties = new HashMap<>(configDruidProperties.getDruid());
        populateDefaultProperties(druidProperties);

        DruidDataSource dataSource;
        try {
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(druidProperties);
        } catch (Exception e) {
            throw new RuntimeException("load datasource error, dbProperties is :" + druidProperties, e);
        }

        return dataSource;
    }

    /**
     * 初始默认值若在配置文件中未设置
     * @param druidProperties
     */
    private void populateDefaultProperties(Map<String, Object> druidProperties) {
        if(druidProperties == null){
            return ;
        }
        druidProperties.putIfAbsent(DruidDataSourceFactory.PROP_FILTERS,"stat");
        druidProperties.putIfAbsent(DruidDataSourceFactory.PROP_INITIALSIZE,"20");
        druidProperties.putIfAbsent(DruidDataSourceFactory.PROP_MAXACTIVE,"50");
        druidProperties.putIfAbsent(DruidDataSourceFactory.PROP_MINIDLE,"20");
        druidProperties.putIfAbsent(DruidDataSourceFactory.PROP_TESTWHILEIDLE,"true");
        druidProperties.putIfAbsent(DruidDataSourceFactory.PROP_CONNECTIONPROPERTIES,"druid.stat.slowSqlMillis=5000");
    }
}
